<template>
  <div id="addSpace">
    <h2 style="margin-bottom: 16px">创建空间</h2>
    <a-form layout="vertical" :model="formData" @finish="handleSubmit">
      <a-form-item label="空间名称" name="spaceName">
        <a-input v-model:value="formData.spaceName" placeholder="请输入空间名称" allow-clear />
      </a-form-item>
      <a-form-item label="空间级别" name="spaceLevel">
        <a-select
          v-model:value="formData.spaceLevel"
          :options="SPACE_LEVEL_OPTIONS"
          placeholder="请输入空间级别"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%" :loading="loading">
          创建
        </a-button>
      </a-form-item>
    </a-form>
    <a-card title="空间级别介绍">
      <a-typography-paragraph>
        * 目前仅支持开通普通版，如需升级空间，请联系
        <a href="https://gitee.com/dshabao" target="_blank">管理员</a>。
      </a-typography-paragraph>
      <a-typography-paragraph v-for="spaceLevel in spaceLevelList" :key="spaceLevel">
        {{ spaceLevel.text }}：大小 {{ convertByteToMb(spaceLevel.maxSize) }} MB， 数量
        {{ spaceLevel.maxCount }}
      </a-typography-paragraph>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import {
  addSpaceUsingPost,
  getSpaceLevelUsingGet,
  getSpaceVoByIdUsingGet,
  updateSpaceUsingPost,
} from '@/api/spaceController'
import { SPACE_LEVEL_ENUM, SPACE_LEVEL_OPTIONS } from '@/constants/space'
import { message } from 'ant-design-vue'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()
const id = route.query.id
const oldSpace = ref<API.SpaceVO>()
const formData = reactive<API.SpaceAddRequest | API.SpaceUpdateRequest>({
  spaceName: '',
  spaceLevel: SPACE_LEVEL_ENUM.COMMON,
})
const loading = ref(false)
const spaceLevelList = ref<API.SpaceLevel[]>([])

//获取空间级别列表
const getSpaceLevelList = async () => {
  const res = await getSpaceLevelUsingGet()
  if (res.data.code === 0 && res.data.data) {
    spaceLevelList.value = res.data.data
  } else {
    message.error('获取空间级别列表失败' + res.data.message)
  }
}

//获取老数据
const getOldSpace = async () => {
  const res = await getSpaceVoByIdUsingGet({ id: id })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data
    oldSpace.value = data
    formData.spaceName = data.spaceName
    formData.spaceLevel = data.spaceLevel
  }
}

// 提交表单
const handleSubmit = async () => {
  loading.value = true
  const spaceId = oldSpace.value?.id
  let res

  //更新
  if (spaceId) {
    res = await updateSpaceUsingPost({
      id: spaceId,
      ...formData,
    })
  } else {
    //创建
    res = await addSpaceUsingPost({
      ...formData,
    })
  }
  if (res.data.code === 0 && res.data.data) {
    message.success('操作成功')
    router.push({
      path: `/space/${res.data.data}`,
    })
  } else {
    message.error('操作失败' + res.data.message)
  }
  loading.value = false
}

//格式化字节为MB
const convertByteToMb = (byteValue: number | string | null | undefined) => {
  if (byteValue === null || byteValue === undefined) {
    return '0'
  }
  const byte = Number(byteValue)
  if (isNaN(byte)) {
    return '0'
  }
  const mb = byte / (1024 * 1024)
  return mb
    .toFixed(2)
    .replace(/\.00$/, '')
    .replace(/(\.\d)0$/, '$1')
}
onMounted(() => {
  getSpaceLevelList()
  getOldSpace()
})
</script>

<style lang="scss" scoped>
#addSpace {
  max-width: 720px;
  margin: 0 auto;
}
</style>
